<?php

class Ebx_Autoloader {

	protected $_basePaths = array();

	protected $_libIncluded = false;

	protected $_packageSeparator = '_';

	protected $_separator = DIRECTORY_SEPARATOR;

	function __construct($path = null) {
		if ($path !== null) {
			$this->addBasePath($path);
		}
	}

	function addBasePath($path) {
		if (is_string($path)) {
			$this->_basePaths[] = $path;
		}
	}

	function init() {
		$this->_init();
	}

	function autoload($className) {
		if (!class_exists($className)) {
			foreach ($this->_basePaths as $path) {
				$path = $this->_normalizeBasePath($path);
				if (!$this->_libIncluded) {
					include $path.'Core.php';
					$this->_libIncluded = true;
					if (class_exists($className)) {
						return true;
					}
				}

				$classPath = $this->_getClassPath($className, $path);
				if (file_exists($classPath)) {
					include $classPath;
				}
			}
		}
	}

	protected function _init() {
		if (!function_exists('spl_autoload_register')) {
			trigger_error("function spl_autoload_register not exists", E_USER_ERROR);
			return false;
		}
		$stack = array(
			array($this, 'autoload'),
		);

		if (function_exists('__autoload')) {
			array_unshift($stack, '__autoload');
		}

		foreach ($stack as $item) {
			spl_autoload_register($item);
		}

	}

	protected function _normalizeBasePath($path) {
		return rtrim($path, '\\/').'/';
	}

	protected function _getClassPath($className, $basePath) {
		$className = str_replace($this->_packageSeparator, $this->_separator, $className);
		return $basePath.$className.'.php';
	}

}

?>